package lj.netty;

import cn.hutool.core.lang.Opt;
import cn.hutool.log.StaticLog;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import ntd.util.UtilCatch;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * netty - tcp 使用封装
 */
public class ComNettyTcpClient extends ComAbsNettyTcp implements ComNetty {

    public final Bootstrap bootstrap = new Bootstrap();

    public ComNettyTcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 启动监听
     */
    public void start() {
        bootstrap.group(workerGroup) // 1.指定线程模型
                .channel(NioSocketChannel.class) // 2.指定 IO 类型为 NIO
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        // 分包器
                        Opt.ofNullable(ljNettyInitContext.getLJCNettyListen()).ifPresent(ljcNettyListen -> ch.pipeline().addLast(ljcNettyListen.struct()));
                        // 监听器
                        ch.pipeline().addLast(ljNettyInitContext.getChannelHandlerCommon());
                    }
                });

        // 4.建立连接
        UtilCatch.tryCatchNoRes(() -> {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            StaticLog.info("tcp-client[{}:{}]链接成功", host, port);
            channelFuture.channel().closeFuture().sync();
            StaticLog.info("tcp-client[{}:{}]链接关闭", host, port);
        });
    }

    public boolean conn() {

        AtomicBoolean isSuccess = new AtomicBoolean(false);

        try {
            bootstrap.connect(host, port).addListener(future -> isSuccess.set(future.isSuccess())).sync();
        } catch (Throwable e) {
            StaticLog.error(e);
            return false;
        }

        StaticLog.info("tcp-client[{}:{}]链接结果 - {}", host, port, isSuccess.get());

        return isSuccess.get();
    }

}
